package com.qtu.gateway.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.qtu.gateway.feign.GatewayFeignService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE;

@Component
public class LoginFilter extends ZuulFilter {

    @Autowired
    private GatewayFeignService gatewayFeignService;

    /**
     * 过滤器类型
     *     PRE_TYPE：前置过滤器（经过路由之前）
     *     ROUTE_TYPE：路由过滤器（将请求路由到对应的微服务时执行）
     *     POST_TYPE：后置过滤器（将请求路由到对应的微服务后执行）
     *     ERROR_TYPE：错误过滤器（在其它阶段发生错误时执行）
     */
    @Override
    public String filterType() {
        return PRE_TYPE;
    }

    /**
     * 过滤器执行顺序
     *      数字小先执行
     */
    @Override
    public int filterOrder() {
        return 0;
    }

    /**
     * 确定过滤器是否过滤
     *      true:拦截 false：放行
     */
    int i = 1;
    @Override
    public boolean shouldFilter() {
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();
        System.err.println("第("+ i++ +")次请求："+request.getRequestURI());
        if("/gate/user/api/seller/getLogin".equals(request.getRequestURI()) || "/gate/user/login".equals(request.getRequestURI())){
            return false;//1、登录请求，放行
        }
        String token = request.getParameter("token");//2、验证 token令牌
        if(!StringUtils.isEmpty(token)){
            String exists = gatewayFeignService.exists(token);
            if(StringUtils.equals("true",exists)){
                return false;//3、已登录，放行
            }
            return true;//4、token不存在，登录信息已经失效，拦截...
        }
        return true; //5、未登录、非法访问，拦截...
    }

    /**
     * 执行拦截处理
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {
        RequestContext context = RequestContext.getCurrentContext();
        context.setSendZuulResponse(false);//拦截路径
        context.setResponseStatusCode(401);
        return null;
    }
}
